package xyz.xiangyushui.controller.membership.pointsToBalance;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import xyz.xiangyushui.dao.user.member.MembershipDao;

/**
 * Servlet implementation class PointsToBalancePost
 */
@WebServlet("/member/pointsToBalancePost")
public class PointsToBalancePost extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MembershipDao md;
	private final String invalidQuantity = "invalid quantity!";
	private final String insufficientQuantity = "insufficient quantity in your account!";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public PointsToBalancePost() {
		super();
		md = new MembershipDao();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String quantity = request.getParameter("quantity");
		String user = (String) request.getSession(false).getAttribute("userName");
		String msg=validate(quantity, user);
		
		if(msg.equals("success")){
			//5积分换1元
			md.changePoints(user, 0-Integer.parseInt(quantity));
			md.changeBalance(user, Double.parseDouble(quantity)/5.0);
		}else{
			request.setAttribute("failedMsg", msg);
		}
		request.getRequestDispatcher("/member/pointsToBalance").forward(request, response);
		
	}

	private String validate(String quantity,String user){
		try{
			int q=Integer.parseInt(quantity);
			if(q<=0){
				return invalidQuantity;
			}else{
				if(q>md.getPoints(user)){
					return insufficientQuantity;
				}
			}
		}catch(NumberFormatException e){
			return invalidQuantity;
		}
		return "success";
	}

}
